/**
 * Created with CLion.
 * Description: 
 * User: loong
 * Date: 2021/6/20
 * Time: 22:36
 */

#include "PngDaoWidget.h"

PngDaoWidget::PngDaoWidget(QWidget * parent)
    : QWidget(parent)
    , lineEdit_(new QLineEdit)
    , png_label_(new QLabel)
    , tableView_(new QTableView)
    , buttonGroup_(new QButtonGroup)
{
    InitDB();
    InitWidgets();
    InitUi();
    InitEvent();
}

PngDaoWidget::~PngDaoWidget()
{
    if(database_obj_.isOpen())
        database_obj_.close();
}

void PngDaoWidget::InitWidgets()
{
    lineEdit_->setPlaceholderText("选择数据库文件!");

    btn_map_.insert("选择", new QPushButton(QIcon(GetPng("选择")), "选择"));
    btn_map_.insert("连接", new QPushButton(QIcon(GetPng("连接")), "连接"));
    btn_map_.insert("断开", new QPushButton(QIcon(GetPng("断开")), "断开"));
    btn_map_.insert("导入", new QPushButton(QIcon(GetPng("导入")), "导入"));
    btn_map_.insert("导出", new QPushButton(QIcon(GetPng("导出")), "导出"));
    btn_map_.insert("删除", new QPushButton(QIcon(GetPng("删除")), "删除"));
    btn_map_.insert("重排", new QPushButton(QIcon(GetPng("重排")), "重排"));
    btn_map_.insert("去重", new QPushButton(QIcon(GetPng("去重")), "去重"));
}

void PngDaoWidget::InitUi()
{
    auto main_layout = new QGridLayout(this);

    main_layout->addWidget(lineEdit_, 0, 0);
    main_layout->addWidget(btn_map_.value("选择"), 0, 1);
    main_layout->addWidget(btn_map_.value("连接"), 1, 0, Qt::AlignRight);
    main_layout->addWidget(btn_map_.value("断开"), 1, 1, Qt::AlignRight);

    main_layout->addWidget(png_label_, 0, 2, 2, 2);
    main_layout->addWidget(tableView_, 2, 0, 5, 2);

    auto btn_layout = new QVBoxLayout();
    btn_layout->addWidget(btn_map_.value("导入"));
    btn_layout->addWidget(btn_map_.value("导出"));
    btn_layout->addWidget(btn_map_.value("删除"));
    btn_layout->addWidget(btn_map_.value("重排"));
    btn_layout->addWidget(btn_map_.value("去重"));

    main_layout->addLayout(btn_layout, 2, 2, 5, 2);
}

void PngDaoWidget::InitEvent()
{
    connect(btn_map_.value("选择"), &QPushButton::clicked, this, [=]() {
        QString path = QFileDialog::getOpenFileName(this, "选择资源文件", QCoreApplication::applicationDirPath() + "/../../../", "*.db");
        lineEdit_->setText(path);
    });

    connect(btn_map_.value("连接"), &QPushButton::clicked, this, [=]() {
        /*[1] 连接数据库 */
        if(QSqlDatabase::contains("res"))
            database_obj_ = QSqlDatabase::database("res");
        else {
            database_obj_ = QSqlDatabase::addDatabase("QSQLITE", "res");
            database_obj_.setDatabaseName(lineEdit_->text());
        }

        if(!database_obj_.open())
            qInfo() << database_obj_.lastError();
        else {
            qInfo() << "连接成功";
            lineEdit_->setEnabled(false);
        }
    });

    connect(btn_map_.value("断开"), &QPushButton::clicked, this, [=]() {
        if(database_obj_.isOpen()) {
            database_obj_.close();
            qInfo() << "断开成功";
            lineEdit_->setEnabled(true);
        }
        else {
            qInfo() << "数据库为尚未连接!";
        }
    });

    connect(btn_map_.value("导入"), &QPushButton::clicked, this, [=]() {
        auto file_name = QFileDialog::getOpenFileNames(this, "选择导入文件", QStandardPaths::standardLocations(QStandardPaths::StandardLocation::PicturesLocation).first(), "*.png;*.svg;");

        if(!file_name.isEmpty())
            InsertPng(file_name);
    });
}

void PngDaoWidget::InsertPng(const QString & file_name)
{
    QFileInfo file(file_name);
    QSqlQuery insert_query(database_obj_);
    insert_query.prepare(QString(R"(insert into res(name,png) values('%1',:byte);)").arg(file.baseName()));

    QPixmap    pixmap(file.filePath(), "PNG");
    QByteArray inByteArray;
    QBuffer    inBuffer(&inByteArray);
    inBuffer.open(QIODevice::WriteOnly);
    pixmap.save(&inBuffer, "PNG");

    insert_query.bindValue(":byte", inByteArray);

    bool ret = insert_query.exec();
    if(!ret)
        qDebug() << __FILE__ << __LINE__ << insert_query.lastError();
}

void PngDaoWidget::InsertPng(const QDir & dir)
{
    QSqlQuery insert_query(database_obj_);
    insert_query.prepare(R"(insert into res(name,png) values(:name,:byte);)");

    auto file_info_list = dir.entryInfoList(QStringList() << "*.png", QDir::Files | QDir::NoDotAndDotDot);

    for(const auto & file_info : file_info_list) {
        QPixmap    pixmap(file_info.filePath(), "PNG");
        QByteArray inByteArray;
        QBuffer    inBuffer(&inByteArray);
        inBuffer.open(QIODevice::WriteOnly);
        pixmap.save(&inBuffer, "PNG");

        insert_query.bindValue(":name", file_info.baseName());
        insert_query.bindValue(":byte", inByteArray);

        bool ret = insert_query.exec();
        if(!ret)
            qDebug() << __FILE__ << __LINE__ << insert_query.lastError();
    }
}

void PngDaoWidget::InsertPng(const QStringList & file_names)
{
    for(const auto& file : file_names) {
        InsertPng(file);
    }
}

QPixmap PngDaoWidget::GetPng(const QString & png_name)
{
    QSqlQuery png_query(database_obj_);
    png_query.prepare(QString(R"(select png from res where name = '%1';)").arg(png_name));

    if(!png_query.exec())
        qDebug() << __FILE__ << __LINE__ << png_query.lastError();

    png_query.first();
    QByteArray out_bytearray = png_query.value(0).toByteArray();
    QPixmap    ret_pixmap    = QPixmap();
    ret_pixmap.loadFromData(out_bytearray);

    return ret_pixmap;
}

void PngDaoWidget::RemovePng(const QString & png_name)
{
    QSqlQuery delete_query(database_obj_);
    delete_query.prepare(QString(R"(delete from res where name = '%1')").arg(png_name));

    if(!delete_query.exec())
        qDebug() << __FILE__ << __LINE__ << delete_query.lastError();
}

void PngDaoWidget::InitDB()
{
    if(QSqlDatabase::contains("init_res"))
        database_obj_ = QSqlDatabase::database("init_res");
    else {
        database_obj_ = QSqlDatabase::addDatabase("QSQLITE", "init_res");
        database_obj_.setDatabaseName(RES_DB_FILE_PATH);
    }

    if(!database_obj_.open())
        qInfo() << database_obj_.lastError();
    else {
        qInfo() << "连接成功";
        lineEdit_->setEnabled(false);
    }
}
